<?php

namespace App\Services\RecallOvertimeGoldProduct;

use App\Models\GoldRound;
use App\Models\GoldProduct;
use App\Jobs\RecallGoldProductJob;
use Illuminate\Support\Collection;
use App\Events\GoldRecordPaidEvent;
use Illuminate\Support\Facades\Log;
use App\Services\MakeGoldRecord\MakeGoldRecord;

class RecallOvertimeGoldProduct
{
	protected $round;
	
	public function __construct(GoldRound $round)
	{
		$this->round = $round;
	}
	
	protected function execute(Collection $products)
	{
		/**
		 * @var GoldProduct $product
		 */
		foreach ($products as $product) {
			if ($product->is_taken_today) continue;
			if ($product->last_taken_at
				and $product->last_taken_at->isToday()) {
				continue;
			}
			
			if ($mockedUser = mock_user()) {
				
				Log::debug("Make gold product: {$product->id} record");
				
				$record = app(MakeGoldRecord::class, [
					'user' => $mockedUser,
					'pid' => $product
				])->make();
				
				if ($record) {
					event(new GoldRecordPaidEvent($record));
				}
			}
			
			usleep(1000);
		}
	}
	
	protected function runningRecall()
	{
		Log::debug("Round: {$this->round->id} running recalling");
		
		$products = GoldProduct::index($this->round->id)->get();
		
		if ($products->count() <= 0) return;
		
		$this->execute($products);
	}
	
	protected function afterRecall()
	{
		Log::debug("Round: {$this->round->id} after recalling");
		
		$products = GoldProduct::index($this->round->id)->get();
		
		if ($products->count() <= 0) return;
		
		$this->execute($products);
	}
	
	public function recall()
	{
		Log::debug("Recall abort gold product");
		
		if ($this->round->is_recalling) {
			$this->runningRecall();
		}
		if ($this->round->is_after_recalling) {
			$this->afterRecall();
		}
	}
}
